<script setup>
import PageContainer from "@/components/PageContainer.vue";
import { ref } from "vue";
import { Plus,Upload } from "@element-plus/icons-vue";
import { useUserStore } from "@/stores";
import userApi from "@/api/user";
const userStore = useUserStore();
// 解构出图片地址
const {user:{user_pic}} = userStore;
//基于store的代码,初始化我们imageUrl的值
const imgUrl = ref(user_pic);
const uploadRef = ref();
//预览效果实现,基于base64做预览的
const onSelectFile = (file) => {
    // 获取到用户选择的文件
  const filePath = file.raw;
  // 基于文章选择的文件，获取到文件路径
  const reader = new FileReader();
  //获取本地图片的文件路径
  reader.readAsDataURL(filePath);
  reader.onload = () => {
    imgUrl.value = reader.result;
    console.log(imgUrl.value);
  };
};

//上传头像axios 这里是上传的base64图片 
const onUpdateAvatar = async () => {
    //发送请求更新头像
  await userApi.userUpdateAvatar(imgUrl.value);
  // 更新用户信息
  await userStore.getUser();
  // 提示用户
  ElMessage.success("更新头像成功");
};
</script>
<template>
  <PageContainer title="更换头像">
    <el-upload
      ref="uploadRef"
      :auto-upload="false"
      class="avatar-uploader"
      :show-file-list="false"
      :on-change="onSelectFile"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <p></p>

    <el-button
      @click="uploadRef.$el.querySelector('input').click()"
      type="primary"
      :icon="Plus"
      size="large"
      >选择图片</el-button
    >
    <el-button
      @click="onUpdateAvatar"
      type="success"
      :icon="Upload"
      size="large"
      >上传头像</el-button
    >
  </PageContainer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }
    .el-upload {
      border: 1px dashed black;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #f10875;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>